package com.scalar.chiptrack.operations.inventoryps.actioncommands;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.dataentry.LotDetails;
import com.scalar.chiptrack.operations.inventoryps.dao.InventoryPSDao;
import com.scalar.chiptrack.operations.inventoryps.forms.InventoryPackingSlipForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;

public class InventoryPackingSlipSaveCommand extends ActionCommand 
{
	private static final String ACTION_NAME = "/inventoryps.do" ;
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception 
	{
    	InventoryPackingSlipForm inventoryPSForm = (InventoryPackingSlipForm) form;
    	String forwardMapping = "confirmps";

        HashMap<String, String> errors = new HashMap<String, String>();
        HashMap<String, String> info = new HashMap<String, String>();
        String action = request.getParameter("action");

        request.setAttribute(INFO_MESSAGES, info);
        request.setAttribute(ERROR_MESSAGES, errors);

        HttpSession mSession = request.getSession();
        User user = (User) mSession.getAttribute(SessionKeys.USER_KEY);

        if (user == null)
        {
            mSession.setAttribute(SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME);
            return (mapping.findForward("login"));
        }
        else
        {
            if (user.isActionAllowed(Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY))
            {
                request.setAttribute("showMessage", "FALSE");
            }
            else
            {
                request.setAttribute("showMessage", "TRUE");
            }
        }
        
        try
        {
        	if( "confirm".equalsIgnoreCase( action ) )
        	{
        		if ( isTokenValid( request ) )
                {
                    InventoryPSDao.saveInventoryPackingSlip( inventoryPSForm, user );
                    info.put( "Inventory Packing slip saved succesfully", inventoryPSForm.getPackingSlipNumber() );
                    info.put ( "View/Print ,Click here to <a href='javascript:generatePDF("+ inventoryPSForm.getPackingSlipId() +");' onmouseover=\"window.status='Click here to View/print Inventory Packing Slip';return true\" onmouseout=\"window.status='';return true\"> view/print </a>Inventory Packing Slip Details", null );
                    request.removeAttribute( "action" );
                    resetToken( request );
                    inventoryPSForm.setProcessType("0");
                    inventoryPSForm.setBaseprocessType("0");
                    inventoryPSForm.setLocationId(0);
                    inventoryPSForm.setLotId(0);
                    inventoryPSForm.setProcessStepId(0);
                    inventoryPSForm.setSelectedLotsList( null );
                    inventoryPSForm.setAvailableLotsList( null );
                    forwardMapping = "savesuccess";
                }
                else
                {
                    errors.put("Invalid Request" , null );
                }
        	}
        	else
        	{
                ArrayList<LotDetails> selectedList = new ArrayList<LotDetails>();
                LotDetails lotDetails = null;
                for(int i=0; i < inventoryPSForm.getSelectedLotsList().size(); i++ )
                {
                     lotDetails =   inventoryPSForm.getSelectedLotsList().get( i );
                     if ( lotDetails.isChecked() )
                     {
                         selectedList.add(lotDetails);
                     }
                }
                if (selectedList != null && selectedList.size() > 0 )
                {
                    inventoryPSForm.setSelectedLotsList( selectedList );
                }
                
            	if ( inventoryPSForm.getBaseprocessType().equalsIgnoreCase( LOCATION_TYPE_FAB ) || inventoryPSForm.getBaseprocessType().equalsIgnoreCase( LOCATION_TYPE_WAFER_STORE )
                    || inventoryPSForm.getBaseprocessType().equalsIgnoreCase( LOCATION_TYPE_SORT ) || inventoryPSForm.getBaseprocessType().equalsIgnoreCase( LOCATION_TYPE_DIE_BANK )
                    || "Back Grind".equalsIgnoreCase(inventoryPSForm.getProcessType() ) )
            	{
            		request.setAttribute( "showWaferIds", "TRUE" );
            	}
                else
                {
                    request.setAttribute( "showWaferIds", "FALSE" );
                }
            	request.setAttribute( "action", action );
        		forwardMapping = "confirmps";
                saveToken( request );
        	}
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return mapping.findForward( forwardMapping );
	}
	
	private boolean showWaferIds(String psTypeName, String psType, ArrayList<LotDetails> availableLotList) 
	{
		boolean showWaferIds = false;
		if( availableLotList == null || availableLotList.size() == 0 )
		{
			if ( psTypeName.equalsIgnoreCase( LOCATION_TYPE_FAB ) || psTypeName.equalsIgnoreCase( LOCATION_TYPE_WAFER_STORE )
                    || psTypeName.equalsIgnoreCase( LOCATION_TYPE_SORT ) || "Back Grind".equalsIgnoreCase(psType ) )
            {
			    showWaferIds = true;
            }
            else
            {
                showWaferIds = false;
            }
		}
		else
		{
			for( LotDetails	lotDetail:availableLotList )
			{
				if( lotDetail.getWaferIds() != null && lotDetail.getWaferIds().length() > 0 )
				{
					showWaferIds = true;
					break;
				}
			}
		}
		return showWaferIds;
	}
}
